﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using CSharp.Libs.WPF;
using CSharp.Libs.ExceptionHandling;
using CSharp.Libs.Koc;
using KocMapView;
using System.Collections;
using System.Windows.Media;

namespace KocAllianceLister
{
    class AllianceComparerViewModel : ViewModelBase
    {
        #region declarations
        private ObservableCollection<AllianceComparerListItem> _ocAllianceCompareList = new ObservableCollection<AllianceComparerListItem>();
        private ArrayList _aryKoordItems = new ArrayList();
        private ExceptionCollector _EC = null;
        private URLHolder _UH = null;
        SolidColorBrush[] _scbDefinedBrushes = new SolidColorBrush[10];

        private Boolean _fExecuteViewCourt = false;

        #region constants
        private const String DATE_TIME_STAMP_MASK =         "dd.MM.yyyy HH:mm:ss";

        private const String OLD_PARAM_PAGE_NO =            "pageNo";
        private const String OLD_PARAM_CITY_ID =            "cityId";

        private const String PARAM_PER_PAGE =               "perPage";
        private const String PARAM_ALLIANCE_ID =            "allianceId";

        private const String PARAM_PID =                    "pid";

        private const String PARAM_CHECK_ARR =              "checkArr";

        private const String KEY_OK =                       "ok";
        private const String KEY_RESULTS =                  "results";
        private const String KEY_ALLIANCE_ID =              "allianceId";
        private const String KEY_ALLIANCE_NAME =            "allianceName";
        private const String KEY_RANK =                     "rank";
        private const String KEY_USER_ID =                  "userId";
        private const String KEY_DISPLAY_NAME =             "displayName";
        private const String KEY_PLAYER_SEX =               "playerSex";
        private const String KEY_AVATAR_ID =                "avatarId";
        private const String KEY_WAR_STATUS =               "warStatus";
        private const String KEY_MIGHT =                    "might";
        private const String KEY_TITLE =                    "title";
        private const String KEY_OFFICER_TYPE =             "officerType";
        private const String KEY_NUM_CITIES =               "numCities";
        private const String KEY_CITIES =                   "cities";
        private const String KEY_CITY_ID =                  "cityId";
        private const String KEY_CITY_NAME =                "cityName";
        private const String KEY_CITY_X_COORD =             "xCoord";
        private const String KEY_CITY_Y_COORD =             "yCoord";

        private const String KEY_DAILY_ACTION_FLAG  =       "dailyActionFlag";
        private const String KEY_PLAYER_INFO =              "playerInfo";
        private const String KEY_EMAIL =                    "email";
        private const String KEY_FB_UID =                   "fbuid";
        private const String KEY_USER_TYPE =                "usertype";
        private const String KEY_STATUS =                   "status";
        private const String KEY_DATE_JOINED =              "dateJoined";
        private const String KEY_LAST_LOGIN =               "lastLogin";
        private const String KEY_EVENT_TIMESTAMP =          "eventTimestamp";
        private const String KEY_EVENT_STATUS =             "eventStatus";
        private const String KEY_TRUCE_EXPIRE_TIMESTAMP =   "truceExpireTimestamp";
        private const String KEY_FOG_EXPIRE_TIMESTAMP =     "fogExpireTimestamp";
        private const String KEY_CNT_NEWMSG =               "cnt_newmsg";
        private const String KEY_CNT_FRIENDREQ =            "cnt_friendreq";
        private const String KEY_CNT_LOGINS =               "cnt_logins";
        private const String KEY_CNT_PASSRESET =            "cnt_passreset";
        private const String KEY_CNT_CONNECTIONS =          "cnt_connections";
        private const String KEY_PHOTO_HOST =               "photo_host";
        private const String KEY_PHOTO_DIR =                "photo_dir";
        private const String KEY_PHOTO_SUBDIR =             "photo_subdir";
        private const String KEY_PHOTO_NAME =               "photo_name";

        private const String KEY_DATA =                     "data";
        #endregion
        #endregion



        #region constructor / terminator
        public AllianceComparerViewModel(
            ExceptionCollector EC,
            URLHolder UH,
            Boolean ExecuteViewCourt)
        {
            _EC = EC;
            _UH = UH;
            
            _fExecuteViewCourt = ExecuteViewCourt;
            
            _InitUrls();

            _scbDefinedBrushes[0] = Brushes.Red;
            _scbDefinedBrushes[1] = Brushes.Blue;
            _scbDefinedBrushes[2] = Brushes.Green;
            _scbDefinedBrushes[3] = Brushes.Black;
            _scbDefinedBrushes[4] = Brushes.Magenta;
            _scbDefinedBrushes[5] = Brushes.Cyan;
            _scbDefinedBrushes[6] = Brushes.Wheat;
            _scbDefinedBrushes[7] = Brushes.Brown;
            _scbDefinedBrushes[8] = Brushes.Yellow;
            _scbDefinedBrushes[9] = Brushes.DarkGray;

            _ocAllianceCompareList.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(_ocAllianceCompareList_CollectionChanged);
        }

        ~AllianceComparerViewModel()
        {
            _ocAllianceCompareList.CollectionChanged -= _ocAllianceCompareList_CollectionChanged;
            _ocAllianceCompareList = null;
            _UH = null;
            _EC = null;
        }
        #endregion



        #region eventhandling
        void _ocAllianceCompareList_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            Int32 IDX = 0;

            foreach (AllianceComparerListItem ACLI in _ocAllianceCompareList)
            {
                ACLI.Color = _scbDefinedBrushes[IDX++];
            }
        }
        #endregion



        #region private functions
        private void _InitUrls()
        {
            try
            {
                if(_UH.URLAllianceGetOtherInfo.URLMaybeValid)
                {
                    _UH.ParseURLGetUserLeaderboard(_UH.URLAllianceGetOtherInfo.GetURL().Replace(URLHolder.PHP_ALLIANCE_GET_OTHER_INFO, URLHolder.PHP_GET_USER_LEADERBOARD));
                    _UH.URLGetUserLeaderboard.Parameters.Remove(OLD_PARAM_PAGE_NO);
                    _UH.URLGetUserLeaderboard.Parameters.Remove(OLD_PARAM_CITY_ID);
                    _UH.URLGetUserLeaderboard.Parameters.Add(PARAM_ALLIANCE_ID, "");
                    _UH.URLGetUserLeaderboard.Parameters.Add(PARAM_PER_PAGE, 100.ToString());

                    _UH.ParseURLViewCourt(_UH.URLAllianceGetOtherInfo.GetURL().Replace(URLHolder.PHP_ALLIANCE_GET_OTHER_INFO, URLHolder.PHP_VIEW_COURT));
                    _UH.URLViewCourt.Parameters.Remove(OLD_PARAM_PAGE_NO);
                    _UH.URLViewCourt.Parameters.Remove(OLD_PARAM_CITY_ID);
                    _UH.URLViewCourt.Parameters.Add(PARAM_PID, "");

                    _UH.ParseURLGetOnline(_UH.URLAllianceGetOtherInfo.GetURL().Replace(URLHolder.PHP_ALLIANCE_GET_OTHER_INFO, URLHolder.PHP_GET_ONLINE));
                    _UH.URLGetOnline.Parameters.Remove(OLD_PARAM_PAGE_NO);
                    _UH.URLGetOnline.Parameters.Remove(OLD_PARAM_CITY_ID);
                    _UH.URLViewCourt.Parameters.Add(PARAM_CHECK_ARR, "");
                }
                else
                {
                    _EC.AddException(new ArgumentException("Parent URL is not valid."), this.ToString(), _EC.Tools.GetCurrentMethodName());
                }
            }
            catch(Exception ex)
            {
                _EC.AddException(ex, this.ToString(), _EC.Tools.GetCurrentMethodName());
            }
        }

        private void _SetUrl(
            String AllianceId)
        {
            try
            {
                if(_UH.URLAllianceGetOtherInfo.URLMaybeValid)
                {
                    _UH.ParseURLGetUserLeaderboard(_UH.URLAllianceGetOtherInfo.GetURL().Replace(URLHolder.PHP_ALLIANCE_GET_OTHER_INFO, URLHolder.PHP_GET_USER_LEADERBOARD));
                    _UH.URLGetUserLeaderboard.Parameters.Add(PARAM_ALLIANCE_ID, AllianceId);
                    _UH.URLGetUserLeaderboard.Parameters.Add(PARAM_PER_PAGE, 100.ToString());
                }
                else
                {
                    _EC.AddException(new ArgumentException("Parent URL is not valid."), this.ToString(), _EC.Tools.GetCurrentMethodName());
                }
            }
            catch(Exception ex)
            {
                _EC.AddException(ex, this.ToString(), _EC.Tools.GetCurrentMethodName());
            }
        }

        private void _ExecuteURLs()
        {
            try
            {
                if(_UH.URLGetUserLeaderboard.URLMaybeValid)
                {
                    _aryKoordItems.Clear();
                    ArrayList _aryAllianceMembers = new ArrayList();

                    foreach(AllianceComparerListItem ACLI in _ocAllianceCompareList)
                    {
                        _SetUrl(ACLI.AllianceId);

                        Hashtable htResult = null;
                        if(_UH.URLGetUserLeaderboard.GetAnswerHashtable(out htResult))
                        {
                            Boolean fResultOk = false;
                            Boolean.TryParse(htResult[KEY_OK].ToString(), out fResultOk);
                            if(fResultOk)
                            {
                                ArrayList _aryResults = htResult[KEY_RESULTS] as ArrayList;
                                if(_aryResults != null)
                                {
                                    String strCheckArr = "";
                                    Boolean fFirst = true;

                                    foreach(Hashtable HT in _aryResults)
                                    {
                                        try
                                        {
                                            KocAllianceMembersListItem KAMLI = new KocAllianceMembersListItem();

                                            ArrayList aryCities = HT[KEY_CITIES] as ArrayList;
                                            if(aryCities != null)
                                            {
                                                foreach(Hashtable htCity in aryCities)
                                                {
                                                    KocAllianceMembersCityItem KAMCI = new KocAllianceMembersCityItem();

                                                    KAMCI.CityId = htCity[KEY_CITY_ID].ToString();
                                                    KAMCI.CityName = htCity[KEY_CITY_NAME].ToString();
                                                    KAMCI.XCoord = htCity[KEY_CITY_X_COORD].ToString();
                                                    KAMCI.YCoord = htCity[KEY_CITY_Y_COORD].ToString();

                                                    KAMLI.Cities.Add(KAMCI);
                                                }
                                            }

                                            KAMLI.Color = ACLI.Color;

                                            KAMLI.AllianceId = htResult[KEY_ALLIANCE_ID].ToString();
                                            KAMLI.AllianceName = htResult[KEY_ALLIANCE_NAME].ToString();

                                            KAMLI.Rank = HT[KEY_RANK].ToString();
                                            KAMLI.UserId = HT[KEY_USER_ID].ToString();
                                            KAMLI.DisplayName = HT[KEY_DISPLAY_NAME].ToString();
                                            KAMLI.PlayerSex = HT[KEY_PLAYER_SEX].ToString();
                                            KAMLI.AvatarId = HT[KEY_AVATAR_ID].ToString();
                                            KAMLI.WarStatus = HT[KEY_WAR_STATUS].ToString();
                                            try
                                            {
                                                KAMLI.Might = Int32.Parse(HT[KEY_MIGHT].ToString()).ToString("0,000");
                                            }
                                            catch
                                            {
                                            }
                                            KAMLI.Title = HT[KEY_TITLE].ToString();
                                            //KAMLI.OfficerType = HT[KEY_OFFICER_TYPE].ToString();
                                            switch(HT[KEY_OFFICER_TYPE].ToString())
                                            {
                                                case "1":
                                                    KAMLI.OfficerType = "Chancelor";
                                                    break;
                                                case "2":
                                                    KAMLI.OfficerType = "Vice Chancelor";
                                                    break;
                                                case "3":
                                                    KAMLI.OfficerType = "Officer";
                                                    break;
                                                default:
                                                    KAMLI.OfficerType = "";
                                                    break;
                                            }
                                            KAMLI.NumCities = HT[KEY_NUM_CITIES].ToString();

                                            //Build CheckArr parameter
                                            if(fFirst)
                                            {
                                                strCheckArr = KAMLI.UserId;
                                                fFirst = false;
                                            }
                                            else
                                            {
                                                strCheckArr = String.Concat(strCheckArr, ",", KAMLI.UserId);
                                            }

                                            //Get ViewCourt info
                                            if (_fExecuteViewCourt)
                                            {
                                                Hashtable htViewCourt = _GetViewCourt(Int32.Parse(KAMLI.UserId));
                                                if (htViewCourt != null)
                                                {
                                                    Hashtable htPlayerInfo = htViewCourt[KEY_PLAYER_INFO] as Hashtable;
                                                    if (htPlayerInfo != null)
                                                    {
                                                        KAMLI.DailyActionFlag = htViewCourt[KEY_DAILY_ACTION_FLAG].ToString();

                                                        KAMLI.Email = htPlayerInfo[KEY_EMAIL].ToString();
                                                        KAMLI.FBUID = htPlayerInfo[KEY_FB_UID].ToString();
                                                        KAMLI.UserType = htPlayerInfo[KEY_USER_TYPE].ToString();
                                                        KAMLI.Status = htPlayerInfo[KEY_STATUS].ToString();
                                                        KAMLI.DateJoined = htPlayerInfo[KEY_DATE_JOINED].ToString();
                                                        KAMLI.LastLogin = htPlayerInfo[KEY_LAST_LOGIN].ToString();
                                                        KAMLI.EventTimeStamp = htPlayerInfo[KEY_EVENT_TIMESTAMP].ToString();
                                                        KAMLI.EventStatus = htPlayerInfo[KEY_EVENT_STATUS].ToString();
                                                        KAMLI.TruceExpireTimestamp = htPlayerInfo[KEY_TRUCE_EXPIRE_TIMESTAMP].ToString();
                                                        KAMLI.FogExpireTimestamp = htPlayerInfo[KEY_FOG_EXPIRE_TIMESTAMP].ToString();
                                                        KAMLI.CntNewMsg = htPlayerInfo[KEY_CNT_NEWMSG].ToString();
                                                        KAMLI.CntFriendReq = htPlayerInfo[KEY_CNT_FRIENDREQ].ToString();
                                                        KAMLI.CntLogins = htPlayerInfo[KEY_CNT_LOGINS].ToString();
                                                        KAMLI.CntPassReset = htPlayerInfo[KEY_CNT_PASSRESET].ToString();
                                                        KAMLI.CntConnections = htPlayerInfo[KEY_CNT_CONNECTIONS].ToString();
                                                        //KAMLI.PhotoHost = htPlayerInfo[KEY_PHOTO_HOST].ToString();
                                                        //KAMLI.PhotoDir = htPlayerInfo[KEY_PHOTO_DIR].ToString();
                                                        //KAMLI.PhotoSubDir = htPlayerInfo[KEY_PHOTO_SUBDIR].ToString();
                                                        //KAMLI.PhotoName = htPlayerInfo[KEY_PHOTO_NAME].ToString();
                                                    }

                                                }
                                            }

                                            _aryAllianceMembers.Add(KAMLI);
                                        }
                                        catch(Exception ex)
                                        {
                                            _EC.AddException(ex, this.ToString(), _EC.Tools.GetCurrentMethodName());
                                        }
                                    }

                                    //Get Online info
                                    if(strCheckArr != "")
                                    {
                                        _UH.URLGetOnline.Parameters[PARAM_CHECK_ARR] = strCheckArr;

                                        Hashtable htOnline = null;
                                        if(_UH.URLGetOnline.GetAnswerHashtable(out htOnline))
                                        {
                                            if(htOnline != null)
                                            {
                                                fResultOk = false;
                                                Boolean.TryParse(htOnline[KEY_OK].ToString(), out fResultOk);
                                                if(fResultOk)
                                                {
                                                    Hashtable htData = htOnline[KEY_DATA] as Hashtable;
                                                    if(htData != null)
                                                    {
                                                        foreach(KocAllianceMembersListItem KAMLI in _aryAllianceMembers)
                                                        {
                                                            if(htData[KAMLI.UserId] != null &&
                                                               Boolean.Parse(htData[KAMLI.UserId].ToString()))
                                                            {
                                                                KAMLI.Online = "ONLINE";
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    //_strResult = "Server didn't return ArrayList.";
                                }
                            }
                            else
                            {
                                //_strResult = "Server returned false.";
                            }
                        }
                        else
                        {
                            //_strResult = "Execute didn't return true.";
                        }
                    }

                    //Generate KoordItems
                    foreach (KocAllianceMembersListItem KAMLI in _aryAllianceMembers)
                    {
                        foreach (KocAllianceMembersCityItem KAMCI in KAMLI.Cities)
                        {
                            try
                            {
                                KoordItem KI = new KoordItem(
                                    KAMCI.XCoord + "," + KAMCI.YCoord,
                                    KAMLI.DisplayName,
                                    KAMLI.Might,
                                    KAMLI.AllianceName,
                                    KAMCI.CityName,
                                    KAMLI.Online,
                                    KAMLI.LastLogin,
                                    KAMLI.Color);
                                
                                _aryKoordItems.Add(KI);
                            }
                            catch 
                            {
                            }
                        }
                    }
                }
                else
                {
                    //_strResult = "URL is not valid.";
                }
            }
            catch(Exception ex)
            {
                _EC.AddException(ex, this.ToString(), _EC.Tools.GetCurrentMethodName());
            }
        }

        private Hashtable _GetViewCourt(
            Int32 UserId)
        {
            try
            {
                if(UserId > 0)
                {
                    _UH.URLViewCourt.Parameters[PARAM_PID] = UserId.ToString();

                    Hashtable HT=null;
                    _UH.URLViewCourt.GetAnswerHashtable(out HT);

                    if(HT != null)
                    {
                        return HT;
                    }
                }
            }
            catch(Exception ex)
            {
                _EC.AddException(ex, this.ToString(), _EC.Tools.GetCurrentMethodName());
            }

            return null;
        }
        #endregion



        #region interface
        #region properties
        public ObservableCollection<AllianceComparerListItem> AllianceCompareList
        {
            get
            {
                return _ocAllianceCompareList;
            }
        }

        public ArrayList KoordItems
        {
            get
            {
                return _aryKoordItems;
            }
        }
        #endregion

        #region methods
        public void ExecuteURLs()
        {
            _ExecuteURLs();
        }
        #endregion
        #endregion
    }
}
